<template>
  <div>
    <div class="container">
      <!-- 添加viewport meta标签 -->
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
      
      <!-- Top banner -->
      <div>
        <img :src="config.bannerImage" alt="banner" class="responsive-img" />
      </div>
      <!-- Form area -->
      <div class="form-container" :style="{ backgroundImage: `url(${config.backgroundImage})` }">
        <!-- Marquee -->
        <div class="scroll_tips">
          <div class="scroll_box flex flex-align-center">
            <span v-for="(item, index) in config.scrollItems" :key="index" class="scroll_item">{{item}}</span>
          </div>
        </div>
        <div class="phone-box">
          <input
            type="tel"
            inputmode="numeric"
            placeholder="请输入您的手机号码"
            id="tellphone"
            v-model="phoneNumber"
            @focus="handlePhoneInputFocus"
            @input="handlePhoneInputChange"
            maxlength="11"
          />
          <img
            class="hand"
            :src="config.handOneImage"
            alt=""
            :style="{ display: showOneGif ? 'block' : 'none' }"
          />
        </div>
        <div class="msg-box">
          <input
            type="tel"
            inputmode="numeric"
            placeholder="请输入短信验证码"
            id="msgCode"
            v-model="verificationCode"
            maxlength="6"
          />
          <div class="get-flow-code position-y50 flex flex-align-center">
            <span class="line" :style="{ color: config.themeColor }">|</span>
            <p
              class="flex flex-align-center flex-pack-justify-center"
              id="getCode"
              @click="getVerificationCode"
              v-if="!isCountingDown && !isSendingSms"
              :style="{ color: config.themeColor }"
            >
              {{config.verificationCodeText || '获取验证码'}}
            </p>
            <p
              class="flex flex-align-center flex-pack-justify-center countdown"
              v-else-if="isCountingDown"
              :style="{ color: config.themeColor }"
            >
              {{ countdown }}S
            </p>
            <p
              class="flex flex-align-center flex-pack-justify-center sending"
              v-else
              :style="{ color: config.themeColor }"
            >
              发送中...
            </p>
          </div>
          <img
            class="hand1"
            :src="config.handTwoImage"
            alt=""
            :style="{ display: showTwoGif ? 'block' : 'none' }"
          />
          <img
            class="hand2"
            :src="config.handThreeImage"
            alt=""
            style="display: none"
          />
        </div>
        <div id="toApply">
          <div id="toApply_button" class="button_wrap" @click="handleSubmit">
            <img
              class="button button_ani responsive-img"
              :src="config.buttonImage"
              alt="立即办理"
            />
          </div>
          <img
            :src="config.handFourImage"
            class="hand3 position-x50"
            style="display: none"
          />
        </div>
        <!-- Privacy policy checkbox -->
        <div class="privacy-policy">
          <input type="checkbox" id="agree" v-model="isAgreed" />
          <label for="agree">
            我已阅读并同意
            <a href="#" @click.prevent="showPrivacyPolicy" :style="{ color: config.themeColor }">{{config.privacyPolicyText || '隐私政策'}}</a>
          </label>
        </div>

        <!-- Privacy policy popup -->
        <div v-if="showPolicy" class="modal">
          <div class="modal-content">
            <span class="close" @click="closePrivacyPolicy">&times;</span>
            <div class="protocol-title">{{config.privacyPolicyTitle || '隐私政策'}}</div>
            <div class="protocol-content" v-html="config.privacyPolicyContent"></div>
          </div>
        </div>
      </div>
      <!-- Purchase instructions -->
      <div class="notice">
        <img :src="config.noticeImage" alt="notice" class="responsive-img" />
      </div>

      <!-- Toast notification -->
      <div v-if="showModal" class="toast-container">
        <div class="toast">
          <p>{{ modalMessage }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { sendSmsCode, createOrder, reportConversion } from "@/api/telecom/sms";

export default {
  name: "TelecomTemplate",
  props: {
    config: {
      type: Object,
      default: () => ({
        bannerImage: "",
        backgroundImage: "",
        handOneImage: "",
        handTwoImage: "",
        handThreeImage: "",
        handFourImage: "",
        buttonImage: "",
        noticeImage: "",
        themeColor: "#ff0000",
        verificationCodeText: "获取验证码",
        privacyPolicyText: "隐私政策",
        privacyPolicyTitle: "隐私政策",
        privacyPolicyContent: "<p>这是隐私政策内容</p>",
        scrollItems: ["用户1已成功办理", "用户2已成功办理", "用户3已成功办理"]
      })
    }
  },
  data() {
    return {
      phoneNumber: "",
      verificationCode: "",
      scrollInterval: null,
      showOneGif: true,
      showTwoGif: false,
      countdown: 60,
      isCountingDown: false,
      countdownTimer: null,
      extendData: null, // Store extendData returned from the SMS verification code interface
      isSubmitting: false, // Prevent duplicate submissions
      isSendingSms: false, // Prevent clicking send verification code twice at the same time
      isAgreed: false,
      showPolicy: false,
      showModal: false,
      modalMessage: "",
      autoCloseTimer: null
    };
  },
  mounted() {
    // Start scrolling effect
    this.startScroll();
  },
  beforeDestroy() {
    // Clear intervals and timers
    if (this.scrollInterval) {
      clearInterval(this.scrollInterval);
    }
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    if (this.autoCloseTimer) {
      clearTimeout(this.autoCloseTimer);
    }
  },
  methods: {
    // Start scrolling effect for the marquee
    startScroll() {
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval);
      }
      
      this.scrollInterval = setInterval(() => {
        const scrollBox = document.querySelector(".scroll_box");
        if (scrollBox) {
          const firstItem = scrollBox.firstElementChild;
          if (firstItem) {
            scrollBox.style.transition = "transform 0.5s";
            scrollBox.style.transform = "translateY(-100%)";
            
            setTimeout(() => {
              scrollBox.style.transition = "none";
              scrollBox.style.transform = "translateY(0)";
              scrollBox.appendChild(firstItem);
            }, 500);
          }
        }
      }, 3000);
    },
    
    // Handle phone input focus
    handlePhoneInputFocus() {
      this.showOneGif = true;
      this.showTwoGif = false;
    },
    
    // Handle phone input change
    handlePhoneInputChange() {
      // Restrict to numbers only
      this.phoneNumber = this.phoneNumber.replace(/\D/g, "");
      
      // If phone number is complete, show the second animation
      if (this.phoneNumber.length === 11) {
        this.showOneGif = false;
        this.showTwoGif = true;
      }
    },
    
    // Get verification code
    async getVerificationCode() {
      if (!this.phoneNumber || this.phoneNumber.length !== 11) {
        this.showAlert("请输入正确的手机号码");
        return;
      }

      // Already in countdown, don't perform operation
      if (this.isCountingDown) return;

      // Already sending SMS, don't perform operation
      if (this.isSendingSms) return;

      try {
        this.isSendingSms = true; // Set sending status to true

        const response = await sendSmsCode(this.phoneNumber);
        if (response.code === 200) {
          // Save extendData for subsequent ordering
          this.extendData = response.data.extendData;
          // Start countdown
          this.startCountdown();
          this.showAlert("验证码已发送，请注意查收");
        } else {
          this.showAlert(response.msg || "发送验证码失败");
        }
      } catch (error) {
        if (error.message === "获取手机号归属地失败") {
          this.showAlert("获取手机号归属地信息失败，请稍后重试");
        } else if (error.message === "暂不支持该号码归属地的业务办理") {
          this.showAlert(
            "抱歉，暂不支持该号码归属地的业务办理，仅支持广州、佛山、东莞、惠州、江门、湛江地区"
          );
        } else if (error.message === "该号码非中国电信号码，暂不支持办理") {
          this.showAlert("抱歉，该业务仅支持中国电信用户办理");
        } else if (error.message === "网络连接失败，请检查您的网络连接并重试") {
          this.showAlert("网络连接失败，请检查您的网络连接并重试");
        } else if (error.message === "请求超时，请稍后重试") {
          this.showAlert("请求超时，请稍后重试");
        } else {
          this.showAlert("发送验证码失败，请稍后重试");
        }
        console.error("发送验证码出错:", error);
      } finally {
        this.isSendingSms = false; // Whether success or failure, set sending status to false
      }
    },
    
    // Start countdown
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;

      this.countdownTimer = setInterval(() => {
        this.countdown--;

        if (this.countdown <= 0) {
          // Countdown ends
          clearInterval(this.countdownTimer);
          this.isCountingDown = false;
        }
      }, 1000);
    },

    // Handle form submission
    async handleSubmit() {
      if (!this.phoneNumber || !this.verificationCode) {
        this.showAlert("请填写完整信息");
        return;
      }

      if (this.isSubmitting) {
        return; // Prevent duplicate submissions
      }

      if (!this.isAgreed) {
        this.showAlert("请先阅读并同意隐私条款");
        return;
      }

      try {
        this.isSubmitting = true;

        // Show the third animation
        document.querySelector(".hand3").style.display = "block";

        // Call order interface
        const response = await createOrder(
          this.phoneNumber,
          this.verificationCode,
          this.extendData
        );

        if (response.code === 200) {
          // Order success
          this.showAlert("恭喜您，办理成功！");

          // Ensure conversion data is sent to ByteDance
          reportConversion();
          
          // Reset form
          this.phoneNumber = "";
          this.verificationCode = "";
          this.isAgreed = false;
          
          // Hide animations
          this.showOneGif = true;
          this.showTwoGif = false;
          document.querySelector(".hand3").style.display = "none";
          
        } else {
          // Order failed
          this.showAlert(response.msg || "办理失败，请稍后重试");
        }
      } catch (error) {
        if (error.message === "验证码错误") {
          this.showAlert("验证码错误，请重新输入");
        } else if (error.message === "验证码已过期") {
          this.showAlert("验证码已过期，请重新获取");
        } else {
          this.showAlert("办理失败，请稍后重试");
        }
        console.error("提交订单出错:", error);
      } finally {
        this.isSubmitting = false;
        // Hide the third animation
        document.querySelector(".hand3").style.display = "none";
      }
    },
    
    // Show privacy policy
    showPrivacyPolicy() {
      this.showPolicy = true;
    },
    
    // Close privacy policy
    closePrivacyPolicy() {
      this.showPolicy = false;
    },
    
    // Show alert message
    showAlert(message) {
      // Clear any existing timer
      if (this.autoCloseTimer) {
        clearTimeout(this.autoCloseTimer);
      }
      
      this.modalMessage = message;
      this.showModal = true;
      
      // Auto close after 2 seconds
      this.autoCloseTimer = setTimeout(() => {
        this.showModal = false;
      }, 2000);
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 750px;
  margin: 0 auto;
  position: relative;
}

.responsive-img {
  width: 100%;
  display: block;
}

.form-container {
  padding: 20px;
  background-size: cover;
  background-position: center;
  position: relative;
}

/* Scrolling tips */
.scroll_tips {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  padding: 10px 15px;
  margin-bottom: 20px;
  overflow: hidden;
  height: 24px;
}

.scroll_box {
  position: relative;
  height: 24px;
  overflow: hidden;
}

.scroll_item {
  display: block;
  height: 24px;
  line-height: 24px;
  width: 100%;
  text-align: center;
  color: #333;
}

/* Flex utilities */
.flex {
  display: flex;
}

.flex-align-center {
  align-items: center;
}

.flex-pack-justify-center {
  justify-content: center;
}

/* Position utilities */
.position-y50 {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.position-x50 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

/* Input boxes */
.phone-box, .msg-box {
  position: relative;
  margin-bottom: 15px;
}

input[type="tel"] {
  width: 100%;
  height: 50px;
  border-radius: 25px;
  border: 1px solid #ddd;
  padding: 0 20px;
  font-size: 16px;
  box-sizing: border-box;
}

/* Verification code button */
.get-flow-code {
  position: absolute;
  right: 0;
  height: 100%;
  padding-right: 20px;
}

.line {
  margin-right: 10px;
}

.get-flow-code p {
  font-size: 14px;
  cursor: pointer;
}

.countdown, .sending {
  font-size: 14px;
  cursor: default;
}

/* Button */
.button_wrap {
  margin: 20px 0;
  position: relative;
}

.button_ani {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

/* Hand animations */
.hand, .hand1, .hand2, .hand3 {
  position: absolute;
  width: 50px;
  height: auto;
  z-index: 10;
}

.hand {
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.hand1 {
  right: 80px;
  top: 50%;
  transform: translateY(-50%);
}

.hand2 {
  left: 50%;
  bottom: -30px;
  transform: translateX(-50%);
}

.hand3 {
  bottom: -30px;
}

/* Privacy policy */
.privacy-policy {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.privacy-policy input {
  margin-right: 5px;
}

.privacy-policy a {
  text-decoration: underline;
}

/* Modal */
.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  width: 80%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  position: relative;
}

.close {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 24px;
  cursor: pointer;
}

.protocol-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.protocol-content {
  font-size: 14px;
  line-height: 1.6;
}

/* Toast notification */
.toast-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}

.toast {
  padding: 10px 20px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  color: white;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  animation: toastFadeIn 0.3s, toastFadeOut 0.3s 1.7s;
  font-size: 14px;
}

@keyframes toastFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes toastFadeOut {
  from {
    opacity: 1;
    transform: translateY(0);
  }
  to {
    opacity: 0;
    transform: translateY(-20px);
  }
}

/* 修复iOS上的输入框问题 */
input[type="text"],
input[type="tel"],
input[type="number"],
textarea {
  -webkit-appearance: none;
  border-radius: 0;
}

/* 防止iOS缩放 */
@media screen and (max-width: 768px) {
  input[type="text"],
  input[type="tel"],
  input[type="number"],
  textarea {
    font-size: 16px;
  }
}
</style> 